package org.raymond.iworks.study.mq.rabbitmq.classic.pubsub;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author raymond
 * @version V1.0
 * @Description:
 */
@Slf4j
public class EmitLog {
    public final static String EXCHANGE_NAME = "logs";
    public static void main(String[] args) throws Exception {
        String message = "hello fanout";
        send(message);
    }

    private static void send(String message) throws Exception {
        try(Connection conn = connection();
            Channel channel = conn.createChannel()){
            channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
            channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes(StandardCharsets.UTF_8));
            log.info("[x] sent: {}", message);
        } catch (IOException | TimeoutException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection connection() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.0.125");
        factory.setPort(5672);
        factory.setUsername("cloud");
        factory.setPassword("cloud123");
        factory.setVirtualHost("/cloud");
        return factory.newConnection();
    }
}
